package com.pl.code.desktop.core.utils;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.pl.code.desktop.core.data.interfaces.IPackageDataModel;
import com.pl.data.core.interfaces.IFieldFunction;
import com.pl.data.core.utils.FunctionUtil;
import lombok.experimental.UtilityClass;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * @ClasssName DataModelUtil
 * @Description 数据模型工具类
 * @Author Liuyh
 * @Date 2021/10/20
 * @Version V0.0.1
 */
@UtilityClass
public class DataModelUtil {

    /**
     * 通过包名获取类名
     *
     * @param packageName
     * @return
     */
    public String getClassNameByPackageName(String packageName) {
        List<String> list = StrUtil.split(packageName, '.');
        if (CollUtil.isNotEmpty(list)) {
            return list.get(list.size() - 1);
        }
        return null;
    }


    /**
     * 添加包名
     *
     * @param packageName
     */
    public List<String> pushPackage(List<String> packages, String packageName) {
        if (packages == null) {
            packages = new ArrayList<>();
        }
        if (StrUtil.isNotBlank(packageName) && !packages.contains(packageName)) {
            packages.add(packageName);
        }

        return packages;
    }

    /**
     * 添加包名
     *
     * @param packages
     * @param list
     */
    public List<String> pushPackage(List<String> packages, Collection<String> list) {
        if (packages == null) {
            packages = new ArrayList<>();
        }
        if (CollUtil.isNotEmpty(list)) {
            for (String packageName : list) {
                pushPackage(packages, packageName);
            }
        }
        return packages;
    }

    /**
     * 添加包名
     *
     * @param packages
     * @param list<T>
     * @param field
     */
    public <T> List<String> pushPackage(List<String> packages, Collection<T> list, IFieldFunction<T> field) {
        if (packages == null) {
            packages = new ArrayList<>();
        }
        if (CollUtil.isNotEmpty(list)) {
            for (T entity : list) {
                pushPackage(packages,entity,field);
            }
        }
        return packages;
    }

    /**
     * 添加包名
     *
     * @param packages
     * @param entity
     * @param field
     */
    public <T> List<String> pushPackage(List<String> packages, T entity, IFieldFunction<T> field) {
        if (packages == null) {
            packages = new ArrayList<>();
        }
        if (entity != null && entity instanceof IPackageDataModel) {
            IPackageDataModel entityPackageModel = (IPackageDataModel) entity;
            pushPackage(packages, entityPackageModel.getPackageList());
        } else {
            String packageName = FunctionUtil.getFieldValue(entity, field);
            pushPackage(packages, packageName);
        }
        return packages;
    }
}
